import 'dart:async';

import 'package:aero_frisbee/app/state/app_cache_state.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:rongcloud_im_wrapper_plugin/rongcloud_im_wrapper_plugin.dart';

part 'af_conversation_list_view_model.g.dart';

@riverpod
class AfConversationListService extends _$AfConversationListService {
  @override
  FutureOr<List<RCIMIWConversation>> build() async {
    final engine = ref.read(curEngineProvider);
    final completer = Completer<List<RCIMIWConversation>>();
    ref.onDispose(() {
      engine?.onConnectionStatusChanged == null;
    });
    engine?.onMessageReceived =
        (RCIMIWMessage? message, int? left, bool? offline, bool? hasPackage) {
      if (message?.conversationType == RCIMIWConversationType.private) {
        _refresh();
      }
    };
    engine?.onConnectionStatusChanged = (RCIMIWConnectionStatus? status) {
      if (status == RCIMIWConnectionStatus.connected) {
        ///刷新下会话列表
        _refresh();
      }
    };
    engine?.getConversations(
      [RCIMIWConversationType.private],
      null,
      DateTime.now().millisecondsSinceEpoch,
      50,
      callback: IRCIMIWGetConversationsCallback(
        onSuccess: (t) {
          completer.complete(t);
        },
        onError: (code) {
          completer.completeError('fetch data list error');
        },
      ),
    );
    final conversationList = await completer.future;
    return conversationList;
  }

  deleteConversation({required String targetId}) async {
    final engine = ref.read(curEngineProvider);
    await engine?.removeConversation(
      RCIMIWConversationType.private,
      targetId,
      null,
      callback: IRCIMIWRemoveConversationCallback(
        onConversationRemoved: (code) {
          _refresh();
        },
      ),
    );
  }

  _refresh() async {
    final engine = ref.read(curEngineProvider);
    final completer = Completer<List<RCIMIWConversation>>();
    engine?.getConversations(
      [RCIMIWConversationType.private],
      null,
      DateTime.now().millisecondsSinceEpoch,
      50,
      callback: IRCIMIWGetConversationsCallback(
        onSuccess: (t) {
          completer.complete(t);
        },
        onError: (code) {
          completer.completeError('fetch data list error');
        },
      ),
    );
    final conversationList = await completer.future;
    state = AsyncData(conversationList);
  }
}
